package com.lhd.controller;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.lhd.entity.po.CourseInfo;
import com.lhd.entity.po.ExportDataWrapper;
import com.lhd.entity.po.StudentSignInfo;
import com.lhd.entity.vo.ResponseVO;
import com.lhd.service.ExcelService;
import com.alibaba.excel.EasyExcel;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;

@RestController
public class ExcelController extends ABaseController{

    @Autowired
    private ExcelService exportService;

    /**
     * 导出签到记录
     *
     * @param aid 活动ID
     * @return ResponseEntity<byte[]> 包含 Excel 文件
     */
    @GetMapping("/excel/export")
    @ManagedOperation
    public ResponseEntity<byte[]> exportSignInRecords(@RequestParam Integer aid) {
        try {
            ExportDataWrapper dataWrapper = exportService.getExportDataByAid(aid);
            if (dataWrapper == null || dataWrapper.getCourseInfo() == null || dataWrapper.getStudentList() == null || dataWrapper.getStudentList().isEmpty()) {
                return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
            }

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ExcelWriter excelWriter = null;
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();

            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            //设置内容
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            //内容策略
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
            try {
                excelWriter = EasyExcel.write(outputStream).build();
                WriteSheet courseSheet = EasyExcel.writerSheet(0, "签到活动信息")
                        .head(CourseInfo.class)
                        .registerWriteHandler(horizontalCellStyleStrategy)
                        .build();
                excelWriter.write(Collections.singletonList(dataWrapper.getCourseInfo()), courseSheet);
                WriteSheet studentSheet = EasyExcel.writerSheet(1, "具体签到记录")
                        .head(StudentSignInfo.class)
                        .registerWriteHandler(horizontalCellStyleStrategy)
                        .build();
                excelWriter.write(dataWrapper.getStudentList(), studentSheet);
                excelWriter.finish();
            } finally {
                if (excelWriter != null) {
                    excelWriter.finish();
                }
                outputStream.close();
            }

            byte[] excelBytes = outputStream.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDisposition(ContentDisposition.attachment().filename("签到记录.xlsx").build());
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(excelBytes.length);
            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
    /**
     * 从Excel导入用户数据
     * @param file 上传的Excel文件
     * @return 包含导入结果数量的响应实体
     */
    @PostMapping(value = "/excel/import")
    public ResponseVO importUsers(@RequestPart("file") MultipartFile file, @RequestParam("id") Integer id) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                ResponseVO responseVO = new ResponseVO();
                responseVO.setCode(HttpStatus.BAD_REQUEST.value());
                responseVO.setStatus(HttpStatus.BAD_REQUEST.getReasonPhrase());
                responseVO.setData("请选择文件");
                return responseVO;
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (!isValidExcelType(contentType)) {
                ResponseVO responseVO = new ResponseVO();
                responseVO.setCode(HttpStatus.BAD_REQUEST.value());
                responseVO.setStatus(HttpStatus.BAD_REQUEST.getReasonPhrase());
                responseVO.setData("仅支持.xlsx及.xls文件");
                return responseVO;
            }

            // 调用服务层处理导入，将 id 传递给服务层
            Long importedCount = exportService.importUsersFromExcel(file, id);

            // 返回成功响应
            return getSuccessResponseVO("成功导入 " + importedCount + " 条用户数据");
        } catch (IOException e) {
            ResponseVO responseVO = new ResponseVO();
            responseVO.setCode(HttpStatus.BAD_REQUEST.value());
            responseVO.setStatus(HttpStatus.BAD_REQUEST.getReasonPhrase());
            responseVO.setData("文件导入失败: " + e.getMessage());
            return responseVO;
        } catch (Exception e) {
            ResponseVO responseVO = new ResponseVO();
            responseVO.setCode(HttpStatus.BAD_REQUEST.value());
            responseVO.setStatus(HttpStatus.BAD_REQUEST.getReasonPhrase());
            responseVO.setData("文件处理失败: " + e.getMessage());
            return responseVO;
        }
    }
    /**
     * 验证是否为合法的Excel文件类型
     */
    private boolean isValidExcelType(String contentType) {
        return contentType != null && (
                contentType.equals("application/vnd.ms-excel") || // .xls
                        contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") // .xlsx
        );
    }
}